package primetest.impl.service;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;


import javax.inject.Inject;

import primetest.dto.BedDto;
import primetest.dto.WardDto;
import primetest.impl.dao.WardDao;
import primetest.impl.dao.Transaction;
import primetest.impl.service.WardService;


public class WardService implements Serializable {


	/**
	 *
	 */
	private static final long serialVersionUID = -2631043723576104141L;
	private Transaction transaction;
	private WardDao wardDao;

	@Inject
	public WardService(Transaction transaction, WardDao wardDao){
		this.transaction = transaction;
		this.wardDao = wardDao;
	}

	public List<WardDto> getWardList() throws IOException {
		try{
			transaction.begin();
			List<WardDto> wardList = wardDao.getAllList(transaction);
			//transaction.commit();
			return wardList;
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}



	public void addWard(WardDto wardDto) throws IOException {
		try{
			transaction.begin();
			wardDao.addWard(transaction, wardDto);
			transaction.commit();
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}


	public void updateWard(WardDto wardDto) throws IOException {
		try{
			transaction.begin();
			wardDao.updateWard(transaction, wardDto);
			transaction.commit();
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}


	public void deleteWard(String wardSeq) throws IOException {
		try{
			transaction.begin();
			wardDao.deleteWard(transaction, wardSeq);
			transaction.commit();
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}

	public WardDto findWard(String wardSeq) throws IOException {
		try{
			transaction.begin();
			return wardDao.findWard(transaction, wardSeq);
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}

	public List<WardDto> getAllListByBuildingAndDepartment(
			String buildingKey, int departmentSeq) throws IOException {
		try{
			transaction.begin();
			return wardDao.getAllListByBuildingAndDepartment(transaction, buildingKey, departmentSeq);
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}

	public void deleteBed(BedDto selectedBed) throws IOException {
		try{
			transaction.begin();
			WardDto wardDto = wardDao.findWard(transaction, selectedBed.getWardKey());
			if (wardDto != null) {
				wardDto.getBedDtos().remove(selectedBed);
				wardDao.updateWard(transaction, wardDto);
			}
			transaction.commit();
		}catch(IOException e){
			transaction.rollback();
			throw e;
		}
	}

}
